// 服务器开奖逻辑系统 - 根据下注统计来计算最优开奖结果

// 内置配置数据（避免import问题）
const colorConfig = {
    red: [1, 2, 7, 8, 12, 13, 18, 19, 23, 24, 29, 30, 34, 35, 40, 45, 46],
    blue: [3, 4, 9, 10, 14, 15, 20, 25, 26, 31, 36, 37, 41, 42, 47, 48],
    green: [5, 6, 11, 16, 17, 21, 22, 27, 28, 32, 33, 38, 39, 43, 44, 49]
};

const animalConfig = {
    animals: [
        { id: 'rat', name: '鼠', numbers: [6, 18, 30, 42] },
        { id: 'ox', name: '牛', numbers: [5, 17, 29, 41] },
        { id: 'tiger', name: '虎', numbers: [4, 16, 28, 40] },
        { id: 'rabbit', name: '兔', numbers: [3, 15, 27, 39] },
        { id: 'dragon', name: '龙', numbers: [2, 14, 26, 38] },
        { id: 'snake', name: '蛇', numbers: [1, 13, 25, 37, 49], isBenming: true },
        { id: 'horse', name: '马', numbers: [12, 24, 36, 48] },
        { id: 'goat', name: '羊', numbers: [11, 23, 35, 47] },
        { id: 'monkey', name: '猴', numbers: [10, 22, 34, 46] },
        { id: 'rooster', name: '鸡', numbers: [9, 21, 33, 45] },
        { id: 'dog', name: '狗', numbers: [8, 20, 32, 44] },
        { id: 'pig', name: '猪', numbers: [7, 19, 31, 43] }
    ],
    getAnimalByNumber(number) {
        return this.animals.find(animal => animal.numbers.includes(number));
    },
    getAnimalById(id) {
        return this.animals.find(animal => animal.id === id);
    }
};

// 开奖服务器管理器
const LotteryServer = {
    // 下注统计数据结构
    betStatistics: {
        temasDirectBets: {},
        temasSideBets: {},
        zhengmaDirectBets: {},
        zhengmaSideBets: {},
        lianmaBets: {},
        shengxiaoBets: {},
        weishuBets: {},
        buzhongBets: {},
        seboBets: {},
        banboBets: {},
        totalBetAmount: 0
    },

    // 重置下注统计
    resetBetStatistics() {
        this.betStatistics = {
            temasDirectBets: {},
            temasSideBets: {},
            zhengmaDirectBets: {},
            zhengmaSideBets: {},
            lianmaBets: {},
            shengxiaoBets: {},
            weishuBets: {},
            buzhongBets: {},
            seboBets: {},
            banboBets: {},
            totalBetAmount: 0
        };
    },

    // 重置统计数据（别名函数，为了兼容性）
    resetStatistics() {
        return this.resetBetStatistics();
    },

    // 添加投注到统计
    addBetToStatistics(betData) {
        // 添加投注到统计
        
        betData.betDetails.forEach(bet => {
            const amount = bet.amount;
            const odds = bet.odds;
            
            this.betStatistics.totalBetAmount += amount;
            
            // 根据投注类型分类统计
            switch(bet.type) {
                case 'direct':
                    this.addDirectBetStatistics(bet, amount, odds);
                    break;
                case 'sides':
                    this.addSidesBetStatistics(bet, amount, odds);
                    break;
                case 'lianma':
                    this.addLianmaBetStatistics(bet, amount, odds);
                    break;
                case 'shengxiao':
                    this.addShengxiaoBetStatistics(bet, amount, odds);
                    break;
                case 'weishu':
                    this.addWeishuBetStatistics(bet, amount, odds);
                    break;
                case 'buzhong':
                    this.addBuzhongBetStatistics(bet, amount, odds);
                    break;
                case 'sebo':
                    this.addSeboBetStatistics(bet, amount, odds);
                    break;
                case 'banbo':
                    this.addBanboBetStatistics(bet, amount, odds);
                    break;
            }
        });
    },

    // 添加直选投注统计
    addDirectBetStatistics(bet, amount, odds) {
        const category = bet.game === 'tema' ? 'temasDirectBets' : 'zhengmaDirectBets';
        
        if (bet.numbers && bet.numbers.length > 0) {
            bet.numbers.forEach(number => {
                if (!this.betStatistics[category][number]) {
                    this.betStatistics[category][number] = {
                        totalAmount: 0,
                        bets: []
                    };
                }
                
                this.betStatistics[category][number].totalAmount += amount;
                this.betStatistics[category][number].bets.push({
                    ...bet,
                    amount: amount,
                    odds: odds
                });
            });
        }
    },

    // 添加两面投注统计
    addSidesBetStatistics(bet, amount, odds) {
        const category = bet.game === 'tema' ? 'temasSideBets' : 'zhengmaSideBets';
        const key = `${bet.sideType}_${bet.position || 'tema'}`;
        
        if (!this.betStatistics[category][key]) {
            this.betStatistics[category][key] = {
                totalAmount: 0,
                bets: [],
                sideType: bet.sideType,
                position: bet.position
            };
        }
        
        this.betStatistics[category][key].totalAmount += amount;
        this.betStatistics[category][key].bets.push({
            ...bet,
            amount: amount,
            odds: odds
        });
    },

    // 添加连码投注统计
    addLianmaBetStatistics(bet, amount, odds) {
        const key = `${bet.sub}_${bet.numbers ? bet.numbers.sort().join(',') : 'unknown'}`;
        
        if (!this.betStatistics.lianmaBets[key]) {
            this.betStatistics.lianmaBets[key] = {
                totalAmount: 0,
                bets: [],
                subType: bet.sub,
                numbers: bet.numbers
            };
        }
        
        this.betStatistics.lianmaBets[key].totalAmount += amount;
        this.betStatistics.lianmaBets[key].bets.push({
            ...bet,
            amount: amount,
            odds: odds
        });
    },

    // 添加生肖投注统计
    addShengxiaoBetStatistics(bet, amount, odds) {
        const key = `${bet.sub}_${bet.animals ? bet.animals.sort().join(',') : 'unknown'}`;
        
        if (!this.betStatistics.shengxiaoBets[key]) {
            this.betStatistics.shengxiaoBets[key] = {
                totalAmount: 0,
                bets: [],
                subType: bet.sub,
                animals: bet.animals
            };
        }
        
        this.betStatistics.shengxiaoBets[key].totalAmount += amount;
        this.betStatistics.shengxiaoBets[key].bets.push({
            ...bet,
            amount: amount,
            odds: odds
        });
    },

    // 添加尾数投注统计
    addWeishuBetStatistics(bet, amount, odds) {
        const key = `${bet.sub}_${bet.tails ? bet.tails.sort().join(',') : 'unknown'}`;
        
        if (!this.betStatistics.weishuBets[key]) {
            this.betStatistics.weishuBets[key] = {
                totalAmount: 0,
                bets: [],
                subType: bet.sub,
                tails: bet.tails,
                heads: bet.heads
            };
        }
        
        this.betStatistics.weishuBets[key].totalAmount += amount;
        this.betStatistics.weishuBets[key].bets.push({
            ...bet,
            amount: amount,
            odds: odds
        });
    },

    // 添加不中投注统计
    addBuzhongBetStatistics(bet, amount, odds) {
        const key = `${bet.sub}_${bet.numbers ? bet.numbers.sort().join(',') : 'unknown'}`;
        
        if (!this.betStatistics.buzhongBets[key]) {
            this.betStatistics.buzhongBets[key] = {
                totalAmount: 0,
                bets: [],
                subType: bet.sub,
                numbers: bet.numbers
            };
        }
        
        this.betStatistics.buzhongBets[key].totalAmount += amount;
        this.betStatistics.buzhongBets[key].bets.push({
            ...bet,
            amount: amount,
            odds: odds
        });
    },

    // 添加色波投注统计
    addSeboBetStatistics(bet, amount, odds) {
        const key = bet.seboType;
        
        if (!this.betStatistics.seboBets[key]) {
            this.betStatistics.seboBets[key] = {
                totalAmount: 0,
                bets: [],
                seboType: bet.seboType
            };
        }
        
        this.betStatistics.seboBets[key].totalAmount += amount;
        this.betStatistics.seboBets[key].bets.push({
            ...bet,
            amount: amount,
            odds: odds
        });
    },

    // 添加半波投注统计
    addBanboBetStatistics(bet, amount, odds) {
        const key = bet.banbo;
        
        if (!this.betStatistics.banboBets[key]) {
            this.betStatistics.banboBets[key] = {
                totalAmount: 0,
                bets: [],
                banboType: bet.banbo
            };
        }
        
        this.betStatistics.banboBets[key].totalAmount += amount;
        this.betStatistics.banboBets[key].bets.push({
            ...bet,
            amount: amount,
            odds: odds
        });
    },

    // 计算所有可能开奖结果的盈亏
    calculateAllLotteryResults() {
        const results = [];
        
        // 遍历1-49所有可能的特码
        for (let tema = 1; tema <= 49; tema++) {
            // 生成一个完整的开奖结果（特码 + 6个正码）
            const zhengmaNumbers = this.generateZhengmaNumbers(tema);
            const lotteryResult = {
                tema: tema,
                zhengma: zhengmaNumbers,
                allNumbers: [tema, ...zhengmaNumbers]
            };
            
            // 计算该开奖结果的盈亏
            const profitLoss = this.calculateProfitLoss(lotteryResult);
            const netProfit = this.betStatistics.totalBetAmount - profitLoss.totalPayout;
            
            results.push({
                lotteryResult,
                profitLoss,
                netProfit
            });
        }
        
        // 按净盈利降序排序（盈利最高的在前）
        results.sort((a, b) => b.netProfit - a.netProfit);
        
        return results;
    },

    // 生成正码号码（避免与特码重复）
    generateZhengmaNumbers(tema) {
        const availableNumbers = [];
        for (let i = 1; i <= 49; i++) {
            if (i !== tema) {
                availableNumbers.push(i);
            }
        }
        
        // 随机选择6个正码
        const zhengma = [];
        const used = new Set();
        while (zhengma.length < 6) {
            const randomIndex = Math.floor(Math.random() * availableNumbers.length);
            const number = availableNumbers[randomIndex];
            if (!used.has(number)) {
                zhengma.push(number);
                used.add(number);
            }
        }
        
        return zhengma.sort((a, b) => a - b);
    },

    // 计算指定开奖结果的盈亏
    calculateProfitLoss(lotteryResult) {
        const profitLoss = {
            totalPayout: 0,
            details: {
                tema: { payout: 0, details: [] },
                zhengma: { payout: 0, details: [] },
                lianma: { payout: 0, details: [] },
                shengxiao: { payout: 0, details: [] },
                weishu: { payout: 0, details: [] },
                buzhong: { payout: 0, details: [] },
                sebo: { payout: 0, details: [] },
                banbo: { payout: 0, details: [] }
            }
        };
        
        // 计算特码直选赔付
        this.calculateTemasDirectPayout(lotteryResult, profitLoss);
        
        // 计算特码两面赔付
        this.calculateTemasSidesPayout(lotteryResult, profitLoss);
        
        // 计算正码赔付
        this.calculateZhengmaPayout(lotteryResult, profitLoss);
        
        // 计算连码赔付
        this.calculateLianmaPayout(lotteryResult, profitLoss);
        
        // 计算生肖赔付
        this.calculateShengxiaoPayout(lotteryResult, profitLoss);
        
        // 计算尾数赔付
        this.calculateWeishuPayout(lotteryResult, profitLoss);
        
        // 计算不中赔付
        this.calculateBuzhongPayout(lotteryResult, profitLoss);
        
        // 计算色波赔付
        this.calculateSeboPayout(lotteryResult, profitLoss);
        
        // 计算半波赔付
        this.calculateBanboPayout(lotteryResult, profitLoss);
        
        // 计算总赔付
        profitLoss.totalPayout = Object.values(profitLoss.details)
            .reduce((sum, category) => sum + category.payout, 0);
        
        return profitLoss;
    },

    // 计算特码直选赔付
    calculateTemasDirectPayout(lotteryResult, profitLoss) {
        const tema = lotteryResult.tema;
        
        if (this.betStatistics.temasDirectBets[tema]) {
            const betData = this.betStatistics.temasDirectBets[tema];
            let totalPayout = 0;
            
            // 计算实际赔付：只有中奖的投注才计算赔付
            betData.bets.forEach(bet => {
                totalPayout += bet.amount * bet.odds;
            });
            
            profitLoss.details.tema.payout += totalPayout;
            profitLoss.details.tema.details.push({
                type: '特码直选',
                number: tema,
                payout: totalPayout,
                betAmount: betData.totalAmount
            });
        }
    },

    // 计算特码两面赔付
    calculateTemasSidesPayout(lotteryResult, profitLoss) {
        const tema = lotteryResult.tema;
        
        Object.entries(this.betStatistics.temasSideBets).forEach(([key, betData]) => {
            if (this.checkSidesBetWin(tema, betData.sideType, betData.position)) {
                let totalPayout = 0;
                let totalBetAmount = 0;
                
                // 计算实际赔付：只有中奖的投注才计算赔付
                betData.bets.forEach(bet => {
                    totalPayout += bet.amount * bet.odds;
                    totalBetAmount += bet.amount;
                });
                
                profitLoss.details.tema.payout += totalPayout;
                profitLoss.details.tema.details.push({
                    type: '特码两面',
                    sideType: betData.sideType,
                    position: betData.position,
                    payout: totalPayout,
                    betAmount: totalBetAmount
                });
            }
        });
    },

    // 计算正码赔付
    calculateZhengmaPayout(lotteryResult, profitLoss) {
        // 正码直选赔付
        Object.entries(this.betStatistics.zhengmaDirectBets).forEach(([number, betData]) => {
            const num = parseInt(number);
            
            let totalPayout = 0;
            
            // 计算实际赔付：需要根据投注类型检查是否中奖
            betData.bets.forEach(bet => {
                let isWinning = false;
                
                if (bet.sub === 'renxuan') {
                    // 任选：只要号码在正码中就中奖
                    isWinning = lotteryResult.zhengma.includes(num);
                } else if (bet.sub && bet.sub.startsWith('zheng') && bet.sub.endsWith('te')) {
                    // 正N特：需要号码在指定位置才中奖
                    const positionMatch = bet.sub.match(/zheng(\d+)te/);
                    if (positionMatch) {
                        const position = parseInt(positionMatch[1]);
                        if (position >= 1 && position <= 6) {
                            isWinning = lotteryResult.zhengma[position - 1] === num;
                        }
                    }
                } else {
                    // 其他情况，默认按任选处理
                    isWinning = lotteryResult.zhengma.includes(num);
                }
                
                if (isWinning) {
                    totalPayout += bet.amount * bet.odds;
                }
            });
            
            if (totalPayout > 0) {
                profitLoss.details.zhengma.payout += totalPayout;
                profitLoss.details.zhengma.details.push({
                    type: '正码直选',
                    number: num,
                    payout: totalPayout,
                    betAmount: betData.totalAmount
                });
            }
        });
        
        // 正码两面赔付
        Object.entries(this.betStatistics.zhengmaSideBets).forEach(([key, betData]) => {
            const position = parseInt(betData.position);
            if (position >= 1 && position <= 6) {
                const zhengmaNumber = lotteryResult.zhengma[position - 1];
                if (this.checkSidesBetWin(zhengmaNumber, betData.sideType, betData.position)) {
                    let totalPayout = 0;
                    let totalBetAmount = 0;
                    
                    // 计算实际赔付：只有中奖的投注才计算赔付
                    betData.bets.forEach(bet => {
                        totalPayout += bet.amount * bet.odds;
                        totalBetAmount += bet.amount;
                    });
                    
                    profitLoss.details.zhengma.payout += totalPayout;
                    profitLoss.details.zhengma.details.push({
                        type: '正码两面',
                        sideType: betData.sideType,
                        position: betData.position,
                        payout: totalPayout,
                        betAmount: totalBetAmount
                    });
                }
            }
        });
    },

    // 计算连码赔付
    calculateLianmaPayout(lotteryResult, profitLoss) {
        Object.entries(this.betStatistics.lianmaBets).forEach(([key, betData]) => {
            if (this.checkLianmaBetWin(lotteryResult, betData)) {
                let totalPayout = 0;
                let totalBetAmount = 0;
                
                // 计算实际赔付：只有中奖的投注才计算赔付
                betData.bets.forEach(bet => {
                    totalPayout += bet.amount * bet.odds;
                    totalBetAmount += bet.amount;
                });
                
                profitLoss.details.lianma.payout += totalPayout;
                profitLoss.details.lianma.details.push({
                    type: `连码-${betData.subType}`,
                    numbers: betData.numbers,
                    payout: totalPayout,
                    betAmount: totalBetAmount
                });
            }
        });
    },

    // 计算生肖赔付
    calculateShengxiaoPayout(lotteryResult, profitLoss) {
        Object.entries(this.betStatistics.shengxiaoBets).forEach(([key, betData]) => {
            if (this.checkShengxiaoBetWin(lotteryResult, betData)) {
                let totalPayout = 0;
                let totalBetAmount = 0;
                
                // 计算实际赔付：只有中奖的投注才计算赔付
                betData.bets.forEach(bet => {
                    totalPayout += bet.amount * bet.odds;
                    totalBetAmount += bet.amount;
                });
                
                profitLoss.details.shengxiao.payout += totalPayout;
                profitLoss.details.shengxiao.details.push({
                    type: `生肖-${betData.subType}`,
                    animals: betData.animals,
                    payout: totalPayout,
                    betAmount: totalBetAmount
                });
            }
        });
    },

    // 计算尾数赔付
    calculateWeishuPayout(lotteryResult, profitLoss) {
        Object.entries(this.betStatistics.weishuBets).forEach(([key, betData]) => {
            if (this.checkWeishuBetWin(lotteryResult, betData)) {
                let totalPayout = 0;
                let totalBetAmount = 0;
                
                // 计算实际赔付：只有中奖的投注才计算赔付
                betData.bets.forEach(bet => {
                    totalPayout += bet.amount * bet.odds;
                    totalBetAmount += bet.amount;
                });
                
                profitLoss.details.weishu.payout += totalPayout;
                profitLoss.details.weishu.details.push({
                    type: `尾数-${betData.subType}`,
                    tails: betData.tails,
                    heads: betData.heads,
                    payout: totalPayout,
                    betAmount: totalBetAmount
                });
            }
        });
    },

    // 计算不中赔付
    calculateBuzhongPayout(lotteryResult, profitLoss) {
        Object.entries(this.betStatistics.buzhongBets).forEach(([key, betData]) => {
            if (this.checkBuzhongBetWin(lotteryResult, betData)) {
                let totalPayout = 0;
                let totalBetAmount = 0;
                
                // 计算实际赔付：只有中奖的投注才计算赔付
                betData.bets.forEach(bet => {
                    totalPayout += bet.amount * bet.odds;
                    totalBetAmount += bet.amount;
                });
                
                profitLoss.details.buzhong.payout += totalPayout;
                profitLoss.details.buzhong.details.push({
                    type: `不中-${betData.subType}`,
                    numbers: betData.numbers,
                    payout: totalPayout,
                    betAmount: totalBetAmount
                });
            }
        });
    },

    // 计算色波赔付
    calculateSeboPayout(lotteryResult, profitLoss) {
        Object.entries(this.betStatistics.seboBets).forEach(([key, betData]) => {
            if (this.checkSeboBetWin(lotteryResult.tema, betData.seboType)) {
                let totalPayout = 0;
                let totalBetAmount = 0;
                
                // 计算实际赔付：只有中奖的投注才计算赔付
                betData.bets.forEach(bet => {
                    totalPayout += bet.amount * bet.odds;
                    totalBetAmount += bet.amount;
                });
                
                profitLoss.details.sebo.payout += totalPayout;
                profitLoss.details.sebo.details.push({
                    type: `色波-${betData.seboType}`,
                    payout: totalPayout,
                    betAmount: totalBetAmount
                });
            }
        });
    },

    // 计算半波赔付
    calculateBanboPayout(lotteryResult, profitLoss) {
        Object.entries(this.betStatistics.banboBets).forEach(([key, betData]) => {
            if (this.checkBanboBetWin(lotteryResult.tema, betData.banboType)) {
                let totalPayout = 0;
                let totalBetAmount = 0;
                
                // 计算实际赔付：只有中奖的投注才计算赔付
                betData.bets.forEach(bet => {
                    totalPayout += bet.amount * bet.odds;
                    totalBetAmount += bet.amount;
                });
                
                profitLoss.details.banbo.payout += totalPayout;
                profitLoss.details.banbo.details.push({
                    type: `半波-${betData.banboType}`,
                    payout: totalPayout,
                    betAmount: totalBetAmount
                });
            }
        });
    },

    // 检查两面投注是否中奖
    checkSidesBetWin(number, sideType, position) {
        switch(sideType) {
            case 'da': return number >= 25;
            case 'xiao': return number <= 24;
            case 'dan': return number % 2 === 1;
            case 'shuang': return number % 2 === 0;
            case 'dadan': return number >= 25 && number % 2 === 1;
            case 'dashuang': return number >= 25 && number % 2 === 0;
            case 'xiaodan': return number <= 24 && number % 2 === 1;
            case 'xiaoshuang': return number <= 24 && number % 2 === 0;
            case 'hongbo': return colorConfig.red.includes(number);
            case 'lanbo': return colorConfig.blue.includes(number);
            case 'lvbo': return colorConfig.green.includes(number);
            case 'jiaqin': return this.isJiaqin(number);
            case 'yeshou': return this.isYeshou(number);
            default: return false;
        }
    },

    // 检查是否为家禽
    isJiaqin(number) {
        // 家禽对应的号码：牛、马、羊、鸡、狗、猪
        const jiaqinNumbers = [
            ...animalConfig.getAnimalById('ox').numbers,      // 牛：5, 17, 29, 41
            ...animalConfig.getAnimalById('horse').numbers,   // 马：12, 24, 36, 48
            ...animalConfig.getAnimalById('goat').numbers,    // 羊：11, 23, 35, 47
            ...animalConfig.getAnimalById('rooster').numbers, // 鸡：9, 21, 33, 45
            ...animalConfig.getAnimalById('dog').numbers,     // 狗：8, 20, 32, 44
            ...animalConfig.getAnimalById('pig').numbers      // 猪：7, 19, 31, 43
        ];
        return jiaqinNumbers.includes(number);
    },

    // 检查是否为野兽
    isYeshou(number) {
        // 野兽对应的号码：鼠、虎、龙、蛇、猴、兔
        const yeshouNumbers = [
            ...animalConfig.getAnimalById('rat').numbers,     // 鼠：6, 18, 30, 42
            ...animalConfig.getAnimalById('tiger').numbers,   // 虎：4, 16, 28, 40
            ...animalConfig.getAnimalById('dragon').numbers,  // 龙：2, 14, 26, 38
            ...animalConfig.getAnimalById('snake').numbers,   // 蛇：1, 13, 25, 37, 49
            ...animalConfig.getAnimalById('monkey').numbers,  // 猴：10, 22, 34, 46
            ...animalConfig.getAnimalById('rabbit').numbers   // 兔：3, 15, 27, 39
        ];
        return yeshouNumbers.includes(number);
    },

    // 检查连码投注是否中奖
    checkLianmaBetWin(lotteryResult, betData) {
        const betNumbers = betData.numbers || [];
        const allNumbers = lotteryResult.allNumbers;
        const zhengma = lotteryResult.zhengma;
        const tema = lotteryResult.tema;
        
        switch(betData.subType) {
            case 'sanquanzhong':
                return betNumbers.every(num => allNumbers.includes(num));
            case 'sanzhonger':
                return betNumbers.filter(num => allNumbers.includes(num)).length >= 2;
            case 'erquanzhong':
                return betNumbers.every(num => allNumbers.includes(num));
            case 'erzhongte':
                const zhongCount = betNumbers.filter(num => zhengma.includes(num)).length;
                const zhongTe = betNumbers.includes(tema);
                return zhongCount >= 1 || zhongTe;
            case 'techuan':
                return betNumbers.includes(tema) && betNumbers.some(num => zhengma.includes(num));
            default:
                return false;
        }
    },

    // 检查生肖投注是否中奖
    checkShengxiaoBetWin(lotteryResult, betData) {
        const tema = lotteryResult.tema;
        const zhengma = lotteryResult.zhengma;
        const temaAnimal = animalConfig.getAnimalByNumber(tema);
        const zhengmaAnimals = zhengma.map(num => animalConfig.getAnimalByNumber(num)).filter(animal => animal);
        
        const betAnimals = betData.animals || [];
        
        switch(betData.subType) {
            case 'texiao':
                return temaAnimal && betAnimals.includes(temaAnimal.id);
            case 'yixiao':
                return betAnimals.some(animalId => {
                    const animal = animalConfig.getAnimalById(animalId);
                    return animal && (animal.numbers.includes(tema) || animal.numbers.some(num => zhengma.includes(num)));
                });
            case 'zhengxiao':
                return betAnimals.some(animalId => {
                    const animal = animalConfig.getAnimalById(animalId);
                    return animal && animal.numbers.some(num => zhengma.includes(num));
                });
            default:
                return false;
        }
    },

    // 检查尾数投注是否中奖
    checkWeishuBetWin(lotteryResult, betData) {
        const tema = lotteryResult.tema;
        const zhengma = lotteryResult.zhengma;
        const betTails = betData.tails || [];
        const betHeads = betData.heads || [];
        
        switch(betData.subType) {
            case 'tematowei':
                const temaTail = tema % 10;
                const temaHead = Math.floor(tema / 10);
                return betTails.includes(temaTail) || betHeads.includes(temaHead);
            case 'zhengteweishu':
                const allTails = [tema, ...zhengma].map(num => num % 10);
                return betTails.some(tail => allTails.includes(tail));
            default:
                return false;
        }
    },

    // 检查不中投注是否中奖
    checkBuzhongBetWin(lotteryResult, betData) {
        const betNumbers = betData.numbers || [];
        const zhengma = lotteryResult.zhengma;
        
        // 不中投注：选中的号码都不在正码中才算中奖
        return !betNumbers.some(num => zhengma.includes(num));
    },

    // 检查色波投注是否中奖
    checkSeboBetWin(tema, seboType) {
        switch(seboType) {
            case 'hongbo':
                return colorConfig.red.includes(tema);
            case 'lanbo':
                return colorConfig.blue.includes(tema);
            case 'lvbo':
                return colorConfig.green.includes(tema);
            case 'he':
                return false;
            default:
                return false;
        }
    },

    // 检查半波投注是否中奖
    checkBanboBetWin(tema, banboType) {
        const isRed = colorConfig.red.includes(tema);
        const isBlue = colorConfig.blue.includes(tema);
        const isGreen = colorConfig.green.includes(tema);
        const isBig = tema >= 25;
        const isSmall = tema <= 24;
        const isOdd = tema % 2 === 1;
        const isEven = tema % 2 === 0;
        
        switch(banboType) {
            case 'red_big': return isRed && isBig;
            case 'red_small': return isRed && isSmall;
            case 'red_odd': return isRed && isOdd;
            case 'red_even': return isRed && isEven;
            case 'blue_big': return isBlue && isBig;
            case 'blue_small': return isBlue && isSmall;
            case 'blue_odd': return isBlue && isOdd;
            case 'blue_even': return isBlue && isEven;
            case 'green_big': return isGreen && isBig;
            case 'green_small': return isGreen && isSmall;
            case 'green_odd': return isGreen && isOdd;
            case 'green_even': return isGreen && isEven;
            default: return false;
        }
    },

    // 获取最优开奖结果
    getBestLotteryResult() {
        const allResults = this.calculateAllLotteryResults();
        return allResults[0];
    },

    // 获取开奖分析报告
    getLotteryAnalysisReport() {
        const allResults = this.calculateAllLotteryResults();
        const totalBetAmount = this.betStatistics.totalBetAmount;
        
        const maxProfit = allResults[0].netProfit;
        const minProfit = allResults[allResults.length - 1].netProfit;
        const avgProfit = allResults.reduce((sum, result) => sum + result.netProfit, 0) / allResults.length;
        
        const profitableResults = allResults.filter(result => result.netProfit > 0).length;
        const breakEvenResults = allResults.filter(result => result.netProfit === 0).length;
        const lossResults = allResults.filter(result => result.netProfit < 0).length;
        
        return {
            totalBetAmount,
            totalResults: allResults.length,
            maxProfit,
            minProfit,
            avgProfit,
            profitableResults,
            breakEvenResults,
            lossResults,
            profitablePercentage: (profitableResults / allResults.length * 100).toFixed(2),
            topResults: allResults.slice(0, 10),
            worstResults: allResults.slice(-10).reverse(),
            betStatistics: this.betStatistics
        };
    },

    // 获取所有开奖结果按亏损排序
    getAllResultsSortedByLoss() {
        const allResults = this.calculateAllLotteryResults();
        
        // 按净盈利从低到高排序，净盈利相同时按特码号码从低到高排序
        const sortedByLoss = [...allResults].sort((a, b) => {
            if (a.netProfit !== b.netProfit) {
                return a.netProfit - b.netProfit;
            }
            return a.lotteryResult.tema - b.lotteryResult.tema;
        });
        
        return sortedByLoss.map((result, index) => ({
            rank: index + 1,
            tema: result.lotteryResult.tema,
            zhengma: result.lotteryResult.zhengma,
            netProfit: result.netProfit,
            totalPayout: result.profitLoss.totalPayout,
            totalBetAmount: this.betStatistics.totalBetAmount,
            loss: result.netProfit < 0 ? Math.abs(result.netProfit) : 0,
            profit: result.netProfit > 0 ? result.netProfit : 0,
            profitLossDetails: result.profitLoss.details
        }));
    },

    // 获取亏损统计摘要
    getLossStatisticsSummary() {
        const allResults = this.calculateAllLotteryResults();
        const totalBetAmount = this.betStatistics.totalBetAmount;
        
        const lossResults = allResults.filter(result => result.netProfit < 0);
        const profitResults = allResults.filter(result => result.netProfit > 0);
        const breakEvenResults = allResults.filter(result => result.netProfit === 0);
        
        const maxLoss = lossResults.length > 0 ? Math.abs(Math.min(...lossResults.map(r => r.netProfit))) : 0;
        const avgLoss = lossResults.length > 0 ? 
            Math.abs(lossResults.reduce((sum, r) => sum + r.netProfit, 0) / lossResults.length) : 0;
        
        return {
            totalResults: allResults.length,
            totalBetAmount,
            lossResultsCount: lossResults.length,
            profitResultsCount: profitResults.length,
            breakEvenResultsCount: breakEvenResults.length,
            maxLoss,
            avgLoss,
            lossPercentage: (lossResults.length / allResults.length * 100).toFixed(2),
            profitPercentage: (profitResults.length / allResults.length * 100).toFixed(2)
        };
    },

    // 模拟开奖
    simulateLottery(lotteryResult) {
        const profitLoss = this.calculateProfitLoss(lotteryResult);
        const netProfit = this.betStatistics.totalBetAmount - profitLoss.totalPayout;
        
        return {
            lotteryResult,
            profitLoss,
            netProfit,
            summary: {
                totalBetAmount: this.betStatistics.totalBetAmount,
                totalPayout: profitLoss.totalPayout,
                netProfit
            }
        };
    },

    // 获取投注统计摘要
    getBetStatisticsSummary() {
        const totalBetAmount = this.betStatistics.totalBetAmount;
        const categories = {};
        
        categories.tema = {
            direct: Object.keys(this.betStatistics.temasDirectBets).length,
            sides: Object.keys(this.betStatistics.temasSideBets).length
        };
        categories.zhengma = {
            direct: Object.keys(this.betStatistics.zhengmaDirectBets).length,
            sides: Object.keys(this.betStatistics.zhengmaSideBets).length
        };
        categories.lianma = Object.keys(this.betStatistics.lianmaBets).length;
        categories.shengxiao = Object.keys(this.betStatistics.shengxiaoBets).length;
        categories.weishu = Object.keys(this.betStatistics.weishuBets).length;
        categories.buzhong = Object.keys(this.betStatistics.buzhongBets).length;
        categories.sebo = Object.keys(this.betStatistics.seboBets).length;
        categories.banbo = Object.keys(this.betStatistics.banboBets).length;
        
        return {
            totalBetAmount,
            categories
        };
    }
};

// 将LotteryServer添加到全局作用域
window.LotteryServer = LotteryServer; 